package com.xizi.lotterySystem.controller;

import com.xizi.lotterySystem.common.exception.ControllerException;
import com.xizi.lotterySystem.common.exception.errorCode.ControllerErrorCodeException;
import com.xizi.lotterySystem.common.pojo.CommonResult;
import com.xizi.lotterySystem.controller.param.CreateActivityParam;
import com.xizi.lotterySystem.controller.param.PageListParam;
import com.xizi.lotterySystem.controller.result.ActivityInfo;
import com.xizi.lotterySystem.controller.result.CreateActivityResult;
import com.xizi.lotterySystem.controller.result.FindPrizeListResult;
import com.xizi.lotterySystem.controller.result.GetDetailActivityResult;
import com.xizi.lotterySystem.service.IActivityService;
import com.xizi.lotterySystem.dao.dataobject.ActivityDO;
import com.xizi.lotterySystem.service.dto.ActivityDetailDTO;
import com.xizi.lotterySystem.service.dto.CreateActivityDTO;
import com.xizi.lotterySystem.service.enumerate.ActivityPrizeTiersEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

// 活动模块
@RestController
@RequestMapping("/activity")
public class ActivityController {

    Logger log = LoggerFactory.getLogger(ActivityController.class);

    @Autowired
    private IActivityService activityService;

    /**
     * 创建活动
     * @param param
     * @return
     */
    @RequestMapping(value = "/create",method = RequestMethod.POST)
    public CommonResult<CreateActivityResult> createActivity(@RequestBody @Validated CreateActivityParam param){
        //1.校验参数
        if(param == null){
            log.warn("createActivity  param is null");
            throw new ControllerException(ControllerErrorCodeException.PARAM_ERROR);
        }

        CreateActivityDTO createActivityDTO = activityService.createActivity(param);
        CreateActivityResult result = convertToRegisterResult(createActivityDTO);
        return CommonResult.success(result);
    }

    /**
     * 查询活动列表
     * @param param
     * @return
     */
    @RequestMapping("/find-list")
    public CommonResult<FindPrizeListResult<ActivityInfo>> findList(PageListParam param) {

        Long total = activityService.selectCount();
        List<ActivityDO> list = activityService.selectList(param);

        FindPrizeListResult<ActivityInfo> result = new FindPrizeListResult<>();
        result.setTotal(total);
        result.setRecords(convertToActivityInfo(list));

        return CommonResult.success(result);
    }

    /**
     * 获取活动详情信息
     * @param activityId
     * @return
     */
    @RequestMapping("/findDetail")
    public CommonResult<GetDetailActivityResult> findDetail(Long activityId){
        if (activityId == null || activityId < 0){
            log.warn("findDetail : {}",ControllerErrorCodeException.PARAM_ERROR);
            throw new ControllerException(ControllerErrorCodeException.PARAM_ERROR);
        }

        ActivityDetailDTO activityDetailDTO = activityService.selectDetail(activityId);

        return CommonResult.success(convertToGetDetailActivityResult(activityDetailDTO));
    }

    private GetDetailActivityResult convertToGetDetailActivityResult(ActivityDetailDTO activityDetailDTO) {
        if (activityDetailDTO == null){
            log.warn("convertToGetDetailActivityResult : {}",ControllerErrorCodeException.PARAM_ERROR);
            throw new ControllerException(ControllerErrorCodeException.PARAM_ERROR);
        }

        GetDetailActivityResult result = new GetDetailActivityResult();

        result.setActivityId(activityDetailDTO.getActivityId());
        result.setActivityName(activityDetailDTO.getActivityName());
        result.setDescription(activityDetailDTO.getDesc());
        result.setValid(activityDetailDTO.valid());


        result.setPrizes(
                activityDetailDTO.getPrizeDTOList()
                        .stream()
                        .sorted(Comparator.comparingInt(prizeDTO -> prizeDTO.getTiers().getCode()))
                        .map(
                                prizeDTO -> {
                                    GetDetailActivityResult.Prize prize = new GetDetailActivityResult.Prize();
                                    prize.setPrizeId(prizeDTO.getPrizeId());
                                    prize.setName(prizeDTO.getName());
                                    prize.setImageUrl(prizeDTO.getImageUrl());
                                    prize.setPrice(prizeDTO.getPrice());
                                    prize.setDescription(prizeDTO.getDescription());
                                    prize.setPrizeTierName(prizeDTO.getTiers().getTiers());
                                    prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                                    prize.setValid(prizeDTO.valid());
                                    return prize;
                                }
                        ).collect(Collectors.toList())
        );

        result.setUsers(
                activityDetailDTO.getUserDTOList()
                .stream().map(
                                userDTO -> {
                                    GetDetailActivityResult.User user = new GetDetailActivityResult.User();
                                    user.setUserId(userDTO.getUserId());
                                    user.setUserName(userDTO.getUserName());
                                    user.setValid(userDTO.valid());
                                    return user;
                                }
                        ).collect(Collectors.toList())
                );

//        List<GetDetailActivityResult.User> users = new ArrayList<>();
//        for (ActivityDetailDTO.UserDTO userDTO : activityDetailDTO.getUserDTOList()){
//            GetDetailActivityResult.User user = new GetDetailActivityResult.User();
//            user.setUserId(userDTO.getUserId());
//            user.setUserName(userDTO.getUserName());
//            user.setValid(userDTO.valid());
//            users.add(user);
//        }
//
//        result.setUsers(users);
//        List<GetDetailActivityResult.Prize> prizes = new ArrayList<>();
//        for(ActivityDetailDTO.PrizeDTO prizeDTO : activityDetailDTO.getPrizeDTOList()){
//            GetDetailActivityResult.Prize prize = new GetDetailActivityResult.Prize();
//            prize.setPrizeId(prizeDTO.getPrizeId());
//            prize.setName(prizeDTO.getName());
//            prize.setPrice(prizeDTO.getPrice());
//            prize.setPrizeAmount(prizeDTO.getPrizeAmount());
//            prize.setImageUrl(prizeDTO.getImageUrl());
//            prize.setValid(prizeDTO.valid());
//            prize.setDescription(prizeDTO.getDescription());
//            prize.setPrizeTierName(prizeDTO.getTiers().getTiers());
//            prizes.add(prize);
//        }
//
//        result.setPrizes(prizes);
        return result;
    }


    private CreateActivityResult convertToRegisterResult(CreateActivityDTO cAD) {
        if (cAD == null || cAD.getId() <= 0) {
            log.error("convertToRegisterResult() activityId is null or activityId <= 0");
            throw new ControllerException(ControllerErrorCodeException.ACTIVITY_ID_ERROR);
        }
        CreateActivityResult activityResult = new CreateActivityResult();
        activityResult.setActivityId(cAD.getId());
        return activityResult;
    }


    private List<ActivityInfo> convertToActivityInfo(List<ActivityDO> list){
        List<ActivityInfo> listInfo = new ArrayList<>();
        for (ActivityDO activityDTO : list) {
            ActivityInfo activityInfo = new ActivityInfo();
            activityInfo.setActivityId(activityDTO.getId());
            activityInfo.setActivityName(activityDTO.getActivityName());
            activityInfo.setDescription(activityDTO.getDescription());
            activityInfo.setValid(activityDTO.valid());
            listInfo.add(activityInfo);
        }
        return listInfo;
    }
}
